package com.example.demo.easyexcel.dao;

import com.example.demo.easyexcel.db.entity.BaseUser;
import com.example.demo.easyexcel.db.repository.BaseUserRepository;
import com.example.demo.easyexcel.db.repository.CityRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zjq
 * @version 创建时间：2021-12-22 11:04:55
 */

/**
 * 假设这个是你的DAO存储。当然还要这个类让spring管理，当然你不用需要存储，也不需要这个类。
 **/
@Repository
public class BaseUserDAO {

    @Autowired
    private BaseUserRepository baseUserRepository;
    @Autowired
    private CityRepository cityRepository;

    @Transactional
    public void save(List<BaseUser> list) {
        // 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入

        for (int i = 0; i < list.size(); i++) {

            BaseUser baseUser = new BaseUser();
            BaseUser obj = list.get(i);
            String errorMsg = "";


            // 设置姓名
            String name = obj.getName();
            if ("".equals(name)) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "姓名不能为空";
            } else if (name.length() > 32) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "姓名过长";
            } else {
                baseUser.setName(name);
            }


            String sex = obj.getSex();
            if (StringUtils.isNotEmpty(sex)) {
                if ("男".equals(sex)) {
                    baseUser.setSex("1");
                } else if ("女".equals(sex)) {
                    baseUser.setSex("0");
                } else {
                    baseUser.setSex("2");
                }
            }

            // 设置身份证
            String idcard = obj.getIdcard();
            if (StringUtils.isEmpty(idcard)) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "身份证不能为空";
            } else if (idcard.length() > 18) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "身份证过长";
            } else {
                baseUser.setIdcard(idcard);
            }


            // 设置城市
            String city = obj.getCity();
            //根据城市名称来找城市id
            List<Integer> cityid = cityRepository.getCityId(city);
            if (CollectionUtils.isNotEmpty(cityid)) {
                baseUser.setCity(cityid.get(0) + "");
            }
            baseUserRepository.save(baseUser);
        }

    }
}
